package cn.b.sky.mes.pp.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.b.sky.mes.cm.model.ProcessAttachment;
import cn.b.sky.mes.cm.service.ProcessService;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.utils.FTPUtils;
import cn.b.sky.common.utils.SpringBeanUtil;
import cn.b.sky.user.model.Attachment;
import cn.b.sky.user.service.AttachmentService;
import cn.b.sky.mes.pp.model.ProductionControl;
import cn.b.sky.mes.pp.service.ProductionControlService;

@RestController
@RequestMapping("/pp/*")
public class ClientRestController {

  @Resource
  ProductionControlService productionControlService;

  @Resource
  ProcessService processService;

  @Resource
  private AttachmentService attachmentService;

  @RequestMapping("sfc/{siteCode}/{sfcCode}")
  public ProductionControl getSFCData(@PathVariable("siteCode") String siteCode, @PathVariable("sfcCode") String sfcCode) {
    ProductionControl control = productionControlService.selectProductionControl(siteCode, sfcCode);
    control.setProcessOperations(processService.getProcessOperationByProcessCode(siteCode, control.getProcessCode(), control.getProcessRev()));
    return control;
  }

  @RequestMapping("processatt/{siteCode}/{popId}")
  public List<ProcessAttachment> getPopData(@PathVariable("siteCode") String siteCode,
      @PathVariable("popId") Integer popId) {
    if(!StringUtils.isBlank(siteCode) && null != popId){
      return processService.getProcessAttachmentByProcessOperation(popId);
    }
    return null;
  }

  @RequestMapping("attachment/{siteCode}/{attachmentCode}")
  public void showAttachement(HttpServletResponse response, @PathVariable("siteCode") String siteCode,
      @PathVariable("attachmentCode") String attachmentCode) throws IOException {
    if (!StringUtils.isBlank(attachmentCode)) {
      Attachment attachment = attachmentService.selectAttachmentByAttachmentCode(siteCode, attachmentCode);
      if (attachment != null && !StringUtils.isBlank(attachment.getSavePath())) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");

        OutputStream os = response.getOutputStream();
        response.setContentType("image/png");
        FTPUtils ftpUtils = (FTPUtils) SpringBeanUtil.getBean("ftpUtils");
        ftpUtils.fileDownload(attachment.getSavePath(), os);
        os.flush();
        os.close();
      } else {
        throw ImeException.newException("picture.C,doesNotExist.C");
      }

    }
  }
}
